package org.meb.speedway.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.meb.speedway.model.registry.Rider;

public class RiderResolver {

	private List<Rider> riders;
	private Map<String, Rider> cache = new HashMap<String, Rider>();

	public RiderResolver(List<Rider> riders) {
		this.riders = riders;
	}

	public Rider resolve(String riderName) {
		if (cache.containsKey(riderName)) {
			return cache.get(riderName);
		}

		String[] tokens = riderName.toLowerCase().split("\\ +");
		Rider mostHitsRider = null;
		int mostHits = 0;
		for (Rider rider : riders) {
			int hits = 0;
			for (String token : tokens) {
				if (rider.getName().toLowerCase().contains(token)) {
					hits++;
				}
			}
			if (hits > mostHits) {
				mostHitsRider = rider;
				mostHits = hits;
			}
		}

		cache.put(riderName, mostHitsRider);
		return mostHitsRider;
	}
}
